import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: WHY
 * Date: 2023-06-09
 * Time: 19:19
 */
//创建一个类,表示要解析成的对象
class User{
    public String username;
    public String password;
}
@WebServlet("/json")
public class JsonServlet extends HttpServlet {
    //使用jackson,最核心的对象就是ObjectMapper
    //通过这个对象,可以把json字符串解析成Java对象,也可以把一个Java对象转换成json格式字符串
    private ObjectMapper objectMapper=new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过post请求的body传递过来一个json格式的字符串
        //第一个参数表示我要对谁进行解析,第二个参数表示我要把这个对象转换成啥样的对象,此处采用类对象
   User user=     objectMapper.readValue(req.getInputStream(),User.class);
        System.out.println("username="+user.username+",password"+user.password);

        resp.getWriter().write("ok");
    }
}
